﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Aquaculture;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Aquaculture
{
    public class CreateEnterpriceHanler : IRequestHandler<CreateEnterpriceCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Enterprise_Table> _enterpriseRepo;
        private readonly IMapper _mapper;

        public CreateEnterpriceHanler(IBaseRepository<Enterprise_Table> enterpriseRepo, IMapper mapper)
        {
            _enterpriseRepo = enterpriseRepo;
            _mapper = mapper;
        }
        /// <summary>
        /// 养殖公司企业添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateEnterpriceCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var enterprise = _enterpriseRepo.GetAll().Where(p => p.Batch_Id == request.Batch_Id  && p.Traceable_Id==request.Traceable_Id && p.IsDelete == false).FirstOrDefault();
            //如果没有有溯源类型信息为1(养殖)的数据  就添加一条数据
            if (enterprise == null)
            {
                var model = _mapper.Map<Enterprise_Table>(request);
                model.CreateTime = DateTime.Now;
                model.Creater = "张三";
                model.UpdateTime = null;
                var res =_enterpriseRepo.Add(model);
                if (res > 0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "添加成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "添加失败";
                    return Task.FromResult(result);
                }
            }
            else
            {
                enterprise = _mapper.Map(request, enterprise);
                var res = _enterpriseRepo.Update(enterprise);
                if (res > 0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "修改成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "修改失败";
                    return Task.FromResult(result);
                }
            }

        }
    }
}
